package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.TaskInfo;
import com.ruoyi.system.service.ITaskInfoService;
import com.ruoyi.system.service.IUserTaskApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 任务信息管理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/task")
public class TaskInfoController extends BaseController {
    @Autowired
    private ITaskInfoService taskInfoService;
    @Autowired
    private IUserTaskApplyService userTaskApplyService;

    /**
     * 获取任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TaskInfo taskInfo, @RequestParam(value = "excludeSelf", required = false) Boolean excludeSelf) {
        startPage();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录，userId为null
        }
        // 首页传excludeSelf=true时，自动过滤掉自己的任务
        if (excludeSelf != null && excludeSelf && userId != null) {
            taskInfo.setUserId(-userId); // 约定负数为排除
        } else if (taskInfo.getUserId() == null && userId != null) {
            taskInfo.setUserId(userId);
        }
        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo, userId);
        return getDataTable(list);
    }

    /**
     * 导出任务列表
     */
    @Log(title = "任务管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskInfo taskInfo) {
        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo, SecurityUtils.getUserId());
        ExcelUtil<TaskInfo> util = new ExcelUtil<>(TaskInfo.class);
        util.exportExcel(response, list, "任务数据");
    }

    /**
     * 获取任务详细信息
     */
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
        Long userId = SecurityUtils.getUserId();
        TaskInfo taskInfo = taskInfoService.selectTaskInfoById(taskId, userId);

        // 如果查询者是任务的发布者，则额外查询并返回报名者列表
        if (taskInfo != null && taskInfo.getCreateBy().equals(userId.toString())) {
            List<com.ruoyi.common.core.domain.entity.SysUser> applicants = userTaskApplyService.getApplicantsForTask(taskId);
            taskInfo.setApplicants(applicants);
        }

        // 新增：返回当前用户是否已报名和已报名人数
        boolean hasApplied = userTaskApplyService.hasUserApplied(userId, taskId);
        int applyCount = userTaskApplyService.countApplyByTaskId(taskId);

        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("taskInfo", taskInfo);
        data.put("hasApplied", hasApplied);
        data.put("applyCount", applyCount);

        return success(data);
    }

    /**
     * 新增任务
     */
    @Log(title = "任务管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TaskInfo taskInfo) {
        Long userId = null;
        String username = null;
        try {
            userId = SecurityUtils.getUserId();
            username = SecurityUtils.getUsername();
        } catch (Exception e) {
            // 未登录
        }
        if (userId != null) {
            taskInfo.setCreateBy(String.valueOf(userId));
            taskInfo.setUserId(userId);
        } else {
            taskInfo.setCreateBy(null);
        }
        taskInfo.setUsername(username);
        return toAjax(taskInfoService.insertTaskInfo(taskInfo));
    }

    /**
     * 修改任务
     */
    @Log(title = "任务管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TaskInfo taskInfo) {
        Long userId = null;
        String username = null;
        try {
            userId = SecurityUtils.getUserId();
            username = SecurityUtils.getUsername();
        } catch (Exception e) {
            // 未登录
        }
        if (userId != null) {
            taskInfo.setUpdateBy(String.valueOf(userId));
        } else {
            taskInfo.setUpdateBy(null);
        }
        taskInfo.setUpdateName(username);
        return toAjax(taskInfoService.updateTaskInfo(taskInfo));
    }

    /**
     * 删除任务
     */
    @Log(title = "任务管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        return toAjax(taskInfoService.deleteTaskInfoByIds(taskIds));
    }

    /**
     * 根据状态查询任务
     */
    @GetMapping("/status/{status}")
    public AjaxResult getByStatus(@PathVariable Integer status) {
        return success(taskInfoService.selectTaskInfoByStatus(status));
    }

    /**
     * 获取当前用户收藏的任务列表
     */
    @GetMapping("/star/list")
    public TableDataInfo getStarTaskList() {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return getDataTable(new java.util.ArrayList<>());
        }
        List<TaskInfo> list = taskInfoService.selectStarTaskListByUserId(userId);
        return getDataTable(list);
    }

    /**
     * 任务报名
     */
    @PostMapping("/apply/{taskId}")
    public AjaxResult applyTask(@PathVariable Long taskId) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return AjaxResult.error("未登录");
        }
        boolean hasApplied = userTaskApplyService.hasUserApplied(userId, taskId);
        if (hasApplied) {
            // 如果已报名，返回成功状态而不是错误状态
            int applyCount = userTaskApplyService.countApplyByTaskId(taskId);
            java.util.Map<String, Object> data = new java.util.HashMap<>();
            data.put("hasApplied", true);
            data.put("applyCount", applyCount);
            return AjaxResult.success("已报名", data);
        }
        // 新增：校验报名人数上限
        com.ruoyi.system.domain.TaskInfo taskInfo = taskInfoService.selectTaskInfoById(taskId, userId);
        int maxApplyCount = 1;
        if (taskInfo != null && taskInfo.getMaxApplyCount() != null) {
            maxApplyCount = taskInfo.getMaxApplyCount();
        }
        int appliedCount = userTaskApplyService.countApplyByTaskId(taskId);
        if (appliedCount >= maxApplyCount) {
            return AjaxResult.error("报名人数已满");
        }
        userTaskApplyService.applyTask(userId, taskId);
        int applyCount = userTaskApplyService.countApplyByTaskId(taskId);
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("hasApplied", true);
        data.put("applyCount", applyCount);
        return AjaxResult.success("报名成功", data);
    }

    /**
     * 获取当前用户已报名的任务列表
     */
    @GetMapping("/applied/list")
    public TableDataInfo getAppliedTaskList() {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return getDataTable(new java.util.ArrayList<>());
        }
        java.util.List<Long> taskIds = userTaskApplyService.selectTaskIdsByUserId(userId);
        if (taskIds == null || taskIds.isEmpty()) {
            return getDataTable(new java.util.ArrayList<>());
        }
        java.util.List<TaskInfo> list = taskInfoService.selectTaskInfoListByIds(taskIds);
        return getDataTable(list);
    }

    /**
     * 取消报名
     */
    @DeleteMapping("/apply/{taskId}")
    public AjaxResult cancelApplyTask(@PathVariable Long taskId) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return AjaxResult.error("未登录");
        }
        boolean hasApplied = userTaskApplyService.hasUserApplied(userId, taskId);
        if (!hasApplied) {
            return AjaxResult.error("未报名");
        }
        userTaskApplyService.cancelApplyTask(userId, taskId);
        int applyCount = userTaskApplyService.countApplyByTaskId(taskId);
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("hasApplied", false);
        data.put("applyCount", applyCount);
        return AjaxResult.success("取消报名成功", data);
    }

    /**
     * 获取用户任务统计
     */
    @GetMapping("/stats")
    public AjaxResult getUserTaskStats()
    {
        Long userId = SecurityUtils.getUserId();
        if (userId == null)
        {
            // 在这种场景下，返回空的统计数据比返回错误更友好
            java.util.Map<String, Object> emptyStats = new java.util.HashMap<>();
            emptyStats.put("notesCount", 0);
            emptyStats.put("collectsCount", 0);
            emptyStats.put("appliedCount", 0);
            return AjaxResult.success(emptyStats);
        }
        return AjaxResult.success(taskInfoService.getUserStats(userId));
    }

    /**
     * 获取关注用户发布的任务列表
     */
    @GetMapping("/follow/list")
    public TableDataInfo getFollowedUserTaskList() {
        Long userId = SecurityUtils.getUserId();
        startPage();
        List<TaskInfo> list = taskInfoService.selectTasksFromFollowedUsers(userId);
        return getDataTable(list);
    }
}